package br.com.ximp.addessi.client.ui;

import br.com.ximp.addessi.shared.entity.Usuario;
import br.com.ximp.addessi.shared.service.UsuarioSvc;
import br.com.ximp.addessi.shared.service.UsuarioSvcAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.Widget;

public class Layout extends Composite {

	interface MyUiBinder extends UiBinder<Widget, Layout> {}	
	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
	
	@UiField SpanElement  lblUser;
	@UiField LayoutPanel  pnlContent;

	public Layout() {		
		initWidget(uiBinder.createAndBindUi(this));		
		UsuarioSvcAsync userSvc = (UsuarioSvcAsync) GWT.create(UsuarioSvc.class);
		userSvc.getUsuario(new AsyncCallback<Usuario>() {			
			@Override
			public void onSuccess(Usuario result) {
				lblUser.setInnerText(result.getEmail());
			}
			
			@Override
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage(), caught); 
			}
		});
		
		History.addValueChangeHandler(new ValueChangeHandler<String>() {
			
			@Override
			public void onValueChange(ValueChangeEvent<String> event) {
				String token = event.getValue();	
				parseToken(token);
			}
		});
		
		String initToken = History.getToken();
		parseToken(initToken);
	}
	
	private void parseToken(String token){
		pnlContent.clear();
		if (token.startsWith("T")){
			pnlContent.add(new TransacoesUI());
		}else{
			pnlContent.add(new Label("Welcome to section "+token));
		}
	}
}
